﻿using Core.ApiClient.Model;
using Core.DataAccess.Model.Projects;
using Core.Framework.Model.Common;
using Core.Framework.Model.WebSockets;
using Core.Framework.Redis;
using Core.Framework.Redis.Queue_Helper;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;

namespace Core.ApiClient.Controllers
{
    /// <summary>
    /// 系统操作
    /// </summary>
    [Route("/")]
    [ApiController]
    [ApiAuthorize]
    public class SystemController : BaseApiController
    {
        IApplicationLifetime applicationLifetime;

        public SystemController(IApplicationLifetime appLifetime)
        {
            applicationLifetime = appLifetime;
        }



        /// <summary>
        /// 项目在第一次启动的时候需要初始化
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [IgnoreAuthorize]
        public object Ini()
        {
            using (var context = new ProjectContext())
            {
                context.ProjectList.Add(new ProjectList
                {
                    Title = "系统项目",
                    Token = "system"
                });

                context.SaveChanges();

                return 200;
            }
        }



        /// <summary>
        /// 查询数据
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public object Get()
        {
            return WebSocketApplication.ClientsPool;
        }

        /// <summary>
        /// 删除服务客户机信息
        /// </summary>
        /// <returns></returns>
        [HttpPost(".RemoveClientInfo")]
        public IResult RemoveClientInfo(string title)
        {
            if (string.IsNullOrWhiteSpace(title))
            {
                return new ApiResult
                {
                    code = CodeResult.PARAMS_IS_NULL
                };
            }

            var remove = iRedis.HashDelete(RedisQueueHelperParameter.QueueService, $"__QDataBase_{title}_ServiceClinet");

            return new ApiResult
            {
                code = remove ? CodeResult.SUCCESS : CodeResult.DATA_NOT_FOUND
            };
        }

        /// <summary>
        /// 卸载当前服务
        /// </summary>
        /// <returns></returns>
        [HttpPost(".Uninstall")]
        public IResult uni(string token)
        {
            if (!string.IsNullOrWhiteSpace(token))
                if (token == CoreStartupHelper.GetConfigValue("Service:System"))
                {
                    applicationLifetime.StopApplication();
                    return new ApiResult
                    {
                        code = CodeResult.SUCCESS
                    };
                }

            return new ApiResult
            {
                code = CodeResult.SYSTEM_INNER_ERROR
            };
        }
    }
}
